<?php

namespace App\Service\TK\Course;



use App\Models\Cdkey;
use App\Models\Order;
use App\Models\User;
use Carbon\Carbon;
use DB;
use Exception;

class CourseService
{

    // 有效周期
    protected int $courseDays = 365;

    /**
     * 学科购买
     * @param User $user
     * @param int $buyType
     * @param array $params
     * @return bool
     * @throws Exception
     */
    public function buyCourse(User $user, int $buyType=1, array $params=[]): bool
    {
        // 直接购买
        if ($buyType == 1) {
            $order = Order::where('userId', $user->id)->where('id', $params['orderId'])->first();
            if (!$order) throw new Exception('订单无效', 200);
            if ($order->status == 1) throw new Exception('订单未支付', 200);
            if ($order->status == 4) throw new Exception('订单已完成', 200);

            Db::table('tiku_user_has_course')->insert([
                'userId' => $user->id,
                'orderId' => $order->id,
                'courseId' => $order->courseId,
                'status' => 1,  // 状态：1：有效， 2：过期
                'buyAt' => Carbon::now(),
                'expireAt'  => Carbon::now()->addDays($this->courseDays)
            ]);

            return true;
        }

        // 激活码激活
        if ($buyType == 2) {
            // 查激活码
            //$cdkey = Cdkey::where('userId', $user->id)->where('code', $params['cdkey'])->find();
            // change ->
            $cdkey = Cdkey::where('code', $params['cdkey'])->first();

            if (!$cdkey) throw new Exception('激活码无效', 200);
            if ($cdkey->status == 2) throw new Exception('激活码已使用', 200);
            if ($cdkey->status == 3) throw new Exception('激活码未支付', 200);

            Db::table('tiku_user_has_course')->insert([
                'userId' => $user->id,
                'courseId' => $params['courseId'],
                'orderId' => $cdkey->orderId ?? 0,
                'status' => 1,  // 状态：1：有效， 2：过期
                'buyAt' => Carbon::now(),
                'expireAt'  => Carbon::now()->addDays($this->courseDays)
            ]);

            $cdkey->status = 2;    // 状态变更为已使用
            $cdkey->useAt = Carbon::now();
            $cdkey->save();

            return true;
        }

        return false;
    }

}
